/*
* 供应商管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");


// 查询供应商列表
router.get('/list', async (req, res) => {
    console.log("===========查询供应商列表接口============");
    // 获取参数
    let { pageNum, pageSize, vendorCode, vendorName, vendorNick, vendorEn, enableFlag } = req.query;
    // 拼接sql语句
    let sql = "select * from md_vendor";
    let sql_where = ` where 1=1`;
    if(vendorCode){
        sql_where += ` and vendor_code like '%${vendorCode}%'`;
    }
    if(vendorName){
        sql_where += ` and vendor_name like '%${vendorName}%'`;
    }
    if(vendorNick){
        sql_where += ` and vendor_nick like '%${vendorNick}%'`;
    }
    if(vendorEn){
        sql_where += ` and vendor_en like '%${vendorEn}%'`;
    }
    if(enableFlag){
        sql_where += ` and enable_flag = '${enableFlag}'`;
    }
    if(vendorCode || vendorName || vendorNick || vendorEn || enableFlag){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询供应商列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询供应商列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询供应商总数", `select count(*) as count from md_vendor ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询供应商总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询供应商列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询供应商列表成功", data: [], total: 0});
            }
        })
    })
})

// 新增供应商
router.post("/", (req, res)=>{
    console.log("===========新增供应商接口============");
    // 获取参数
    let {address, vendorCode, vendorDes, vendorEn, vendorLogo, vendorName, vendorNick, contact1, contact1Email, contact1Tel, contact2, contact2Email, contact2Tel, creditCode, email, enableFlag, remark, tel, website, vendorLevel, vendorScore} = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断供应商编码和供应商名称是否重复
    db.query("查询供应商编码和供应商名称是否重复", `select * from md_vendor where vendor_code = '${vendorCode}' or vendor_name = '${vendorName}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询供应商编码和供应商名称是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "供应商编码或供应商名称已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into md_vendor (address, vendor_code, vendor_des, vendor_en, vendor_logo, vendor_name, vendor_nick, contact1, 
            contact1_email, contact1_tel, contact2, contact2_email, contact2_tel, credit_code, email, enable_flag, remark, tel, website, create_by, create_time, vendor_level, vendor_score)
        values (${address ? "'"+address+"'" : null}, '${vendorCode}', ${vendorDes ? "'"+vendorDes+"'" : null}, ${vendorEn ? "'"+vendorEn+"'" : null}, 
        ${vendorLogo ? "'"+vendorLogo+"'" : null}, '${vendorName}', ${vendorNick ? "'"+vendorNick+"'" : null},
        ${contact1 ? "'"+contact1+"'" : null}, ${contact1Email ? "'"+contact1Email+"'" : null}, ${contact1Tel ? "'"+contact1Tel+"'" : null}, 
        ${contact2 ? "'"+contact2+"'" : null}, ${contact2Email ? "'"+contact2Email+"'" : null}, ${contact2Tel ? "'"+contact2Tel+"'" : null}, 
        ${creditCode ? "'"+creditCode+"'" : null}, ${email ? "'"+email+"'" : null}, ${enableFlag ? "'"+enableFlag+"'" : null}, ${remark ? "'"+remark+"'" : null},
        ${tel ? "'"+tel+"'" : null}, ${website ? "'"+website+"'" : null}, '${username}', '${createTime}', '${vendorLevel}', '${vendorScore}')`;
        db.query("新增供应商", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增供应商失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增供应商成功"});
            }else{
                res.send({code: 500, msg: "新增供应商失败"});
            }
        })
    })
})

// 查询单个供应商
router.get("/:id", (req, res)=>{
    console.log("===========查询单个供应商接口============");
    // 获取参数
    let id = req.params.id;
    db.query("查询单个供应商", `select * from md_vendor where vendor_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个供应商失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个供应商成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个供应商失败"});
        }
    })
})

// 修改供应商
router.put("/", (req, res)=>{
    console.log("===========修改供应商接口============");
    // 获取参数
    let {vendorId, address, vendorCode, vendorDes, vendorEn, vendorLogo, vendorName, vendorNick, contact1, contact1Email, contact1Tel, contact2, contact2Email, contact2Tel, creditCode, email, enableFlag, remark, tel, website, vendorLevel, vendorScore} = req.body;
    // 获取更新人
    let {username} = verifyToken(req.headers.authorization);
    // 获取更新时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询供应商名称是否重复
    db.query("查询供应商名称是否重复", `select * from md_vendor where vendor_name = '${vendorName}' and vendor_id != ${vendorId}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询供应商名称是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "供应商名称已存在"});
            return;
        }
        // 生成更新sql语句
        let sql = `update md_vendor set address = ${address ? "'"+address+"'" : null}, vendor_des = ${vendorDes ? "'"+vendorDes+"'" : null}, 
        vendor_en = ${vendorEn ? "'"+vendorEn+"'" : null}, vendor_logo = ${vendorLogo ? "'"+vendorLogo+"'" : null}, vendor_name = '${vendorName}',
        vendor_nick = ${vendorNick ? "'"+vendorNick+"'" : null}, contact1 = ${contact1 ? "'"+contact1+"'" : null},
        contact1_email = ${contact1Email ? "'"+contact1Email+"'" : null}, contact1_tel = ${contact1Tel ? "'"+contact1Tel+"'" : null}, contact2 = ${contact2 ? "'"+contact2+"'" : null},
        contact2_email = ${contact2Email ? "'"+contact2Email+"'" : null}, contact2_tel = ${contact2Tel ? "'"+contact2Tel+"'" : null}, credit_code = ${creditCode ? "'"+creditCode+"'" : null},
        email = ${email ? "'"+email+"'" : null}, enable_flag = ${enableFlag ? "'"+enableFlag+"'" : null}, remark = ${remark ? "'"+remark+"'" : null},
        tel = ${tel ? "'"+tel+"'" : null}, website = ${website ? "'"+website+"'" : null}, update_by = '${username}', update_time ='${updateTime}',
        vendor_level = '${vendorLevel}', vendor_score = '${vendorScore}'
        where vendor_id = '${vendorId}'`
        // 执行更新操作
        db.query("更新供应商信息", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "更新供应商信息失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "更新供应商信息成功", data: result});
            }else{
                res.send({code: 500, msg: "更新供应商信息失败"});
            }
            
        })
    })
})

// 删除供应商
router.delete("/:id", (req, res) => {
    console.log("===========删除供应商接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from md_vendor where vendor_id in(${id})`;
    // 查询数据库
    db.query("删除供应商", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除供应商失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除供应商成功"})
        }else{
            res.send({code: 500, msg: "删除供应商失败"})
        }
    })
})


module.exports = router;
